#include "saver.h"
#include <QTextStream>
#include <QStringList>

Saver::Saver(QString filename, GeometryData *data)
{
    filename_ = filename;
    data_ = data;
}

void Saver::save()
{
    QFile file(filename_);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        setErrorMessage("Can't open file");
        emit finished();
        return;
    }
    QTextStream out(&file);

    out << 2 << "\n";

    triangleSaver(data_, out);

   emit finished();
   return;
}

bool Saver::triangleSaver(GeometryData *data,  QTextStream &out)
{

    int progress_prev = 0;

    int point_count = data->points.size();

    out<<point_count << "\n";
    for (int i = 0; i < point_count; i++)
    {

        out<< data->points[i]->x << "  " << data->points[i]->y << "\n";

        int progress =  ((double)i / (double)point_count) * 100;
        if (progress > progress_prev)
        {
            emit progressChanged(progress, "Saving points");
            progress_prev = progress;
        }
    }

    int triangle_count = data->triangles.size();
    int triangle_attrib_count = 4;

    out<<triangle_count<<"\n";

    progress_prev = 0;
    for (int  i = 0; i <  triangle_count; i++)
    {
        int progress =  ((double)i / (double)triangle_count) * 100;
        if (progress > progress_prev)
        {
            emit progressChanged(progress,"Saving triangles");
            progress_prev = progress;
        }
    }
    return 1;
}
